package com.atguigu.gmall.seckill.firstcache;

import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.seckill.service.SeckillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/18 18:24
 */
@Slf4j
@Component
public class SeckillFirstcache {

    private Map<Long, SeckillGoods> secKillCache = new ConcurrentHashMap<>();
    @Autowired
    SeckillGoodsService seckillGoodsService;

    //一级缓存,缓存秒杀商品信息
    public void upSeckillCache(List<SeckillGoods> seckillGoodsList) {
        seckillGoodsList.forEach(goods -> {
            secKillCache.put(goods.getSkuId(), goods);
        });
        log.info("定时任务:一级缓存更新成功,缓存数据量:{}", secKillCache.size());
    }

    //获取秒杀商品信息
    public SeckillGoods getSeckillCache(Long skuId) {
        SeckillGoods seckillGoods = secKillCache.get(skuId);
        if (seckillGoods == null) {
            if (!secKillCache.isEmpty()) {
                //表示没有这个商品的秒杀信息,直接返回null
                log.info("一级缓存中没有数据详细信息,直接返回null");
                return null;
            } else {
                //表示一级缓存没有数据
                //查询数据库,更新一级缓存
                List<SeckillGoods> seckillGoods1 = seckillGoodsService.seckillListCurrDate();
                upSeckillCache(seckillGoods1);
                log.info("一级缓存中没有数据详细信息,查询数据库,更新一级缓存");
                return secKillCache.get(skuId);
            }
        }
        return seckillGoods;
    }

    //获取秒杀商品信息列表
    public List<SeckillGoods> getSeckillCacheList() {
        if (!secKillCache.isEmpty()) {
            //一级缓存中有数据,直接返回
            log.info("一级缓存中有数据,直接返回秒杀商品信息列表");
            return secKillCache.values().stream().sorted(((o1, o2) -> {
                return o1.getStartTime().compareTo(o2.getStartTime());
            })).collect(Collectors.toList());
        }else {
            //一级缓存中没有数据,查询数据库,更新一级缓存,返回
            log.info("一级缓存中没有数据,查询数据库,更新一级缓存,返回秒杀商品信息列表");
            List<SeckillGoods> seckillGoods = seckillGoodsService.seckillListCurrDate();
            return seckillGoods.stream().sorted(((o1, o2) -> {
                return o1.getStartTime().compareTo(o2.getStartTime());
            })).collect(Collectors.toList());
        }
    }
}
